package ernest.frontwindow;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.provider.Settings;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;

import java.text.SimpleDateFormat;


public class FrontWindowActivity extends Activity implements View.OnClickListener {

    /**
     * Called when the activity is first created.
     */
    WindowManager mWindowManager;
    WindowManager.LayoutParams wmParams;
    LinearLayout mFloatLayout;
    LinearLayout mFloatView;
    private Button btnSwitchFullScreen;
    private Button btnRequestOverlays;
    private Button start_Btn;
    private Button btnClose;
    private Button btnCalTime;
    private long startTime;
    private int MSG_TIME = 1001;
    private int REQUEST_DIALOG_PERMISSION = 2001;
    private Handler timeHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            long deltaTime = System.currentTimeMillis() - startTime;
            btnCalTime.setText(deltaTime / 1000 / 60 + ":" + deltaTime / 1000 % 60);
            sendEmptyMessageDelayed(MSG_TIME, 1000);
            if (System.currentTimeMillis() - startTime > 30 * 60 * 1000) {
                btnSwitchFullScreen.setBackgroundColor(Color.RED);
                mFloatView.setBackgroundColor(Color.RED);
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_front_window);
        //初始化控件
        initView();
    }

    @SuppressLint("ClickableViewAccessibility")
    private void createFloatView() {
        //获取LayoutParams对象
        wmParams = new WindowManager.LayoutParams();
        //获取的是LocalWindowManager对象
        mWindowManager = this.getWindowManager();
        //设置window type
        wmParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        //设置图片格式，效果为背景透明
        wmParams.format = PixelFormat.RGBA_8888;
        //设置浮动窗口不可聚焦（实现操作除浮动窗口外的其他可见窗口的操作）
        wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
        //调整悬浮窗显示的停靠位置为左侧置顶
        wmParams.gravity = Gravity.LEFT | Gravity.TOP;
        // 以屏幕左上角为原点，设置x、y初始值，相对于gravity
        wmParams.x = 0;
        wmParams.y = 0;
        //设置悬浮窗口长宽数据
        wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        // 设置悬浮窗口长宽数据
//        wmParams.width = 40;
//        wmParams.height = 40;

        LayoutInflater inflater = this.getLayoutInflater();
        //获取浮动窗口视图所在布局
        mFloatLayout = (LinearLayout) inflater.inflate(R.layout.layout_item, null);
        //浮动窗口按钮
        mFloatView = mFloatLayout.findViewById(R.id.float_id);
        btnSwitchFullScreen = mFloatLayout.findViewById(R.id.btnSwitchFullScreen);
        btnCalTime = mFloatLayout.findViewById(R.id.btnCalTime);
        btnClose = mFloatLayout.findViewById(R.id.btnClose);
        //添加mFloatLayout
        mWindowManager.addView(mFloatLayout, wmParams);


        //绑定触摸移动监听
        mFloatView.setOnTouchListener((v, event) -> {
            wmParams.x = (int) event.getRawX() - mFloatLayout.getWidth() / 2;
            //25为状态栏高度
            wmParams.y = (int) event.getRawY() - mFloatLayout.getHeight() / 2 - 40;
            mWindowManager.updateViewLayout(mFloatLayout, wmParams);
            return false;
        });

        btnClose.setOnClickListener(v -> mWindowManager.removeView(mFloatLayout));
        btnSwitchFullScreen.setOnClickListener(v -> {
            setFullScreen(fullScreen);
            fullScreen = !fullScreen;
        });

        //悬浮框设置点击监听
        mFloatView.setOnClickListener(v -> {

            Toast.makeText(FrontWindowActivity.this, "我是悬浮框", Toast.LENGTH_SHORT).show();
        });

        btnCalTime.setOnClickListener(v -> {
            startTime = System.currentTimeMillis();
            timeHandler.sendEmptyMessage(MSG_TIME);
            btnSwitchFullScreen.setBackgroundColor(Color.BLACK);
            mFloatView.setBackgroundColor(Color.BLACK);
        });

    }

    private boolean fullScreen = false;

    private void setFullScreen(boolean fullScreen) {
        if (fullScreen) {
            btnSwitchFullScreen.setWidth(3000);
            btnSwitchFullScreen.setHeight(getResources().getDisplayMetrics().heightPixels);
        } else {
            btnSwitchFullScreen.setWidth(10);
            btnSwitchFullScreen.setHeight(10);
        }
    }

    private void initView() {
        start_Btn = (Button) findViewById(R.id.start_id);
        btnRequestOverlays = (Button) findViewById(R.id.btnRequestOverlays);
        start_Btn.setOnClickListener(this);
        if (canDrawOverlays()) {
            btnRequestOverlays.setVisibility(View.GONE);
        } else {
            btnRequestOverlays.setVisibility(View.VISIBLE);
        }
        btnRequestOverlays.setOnClickListener(v -> {
            requestSettingCanDrawOverlays();
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.start_id:
                if (null == mWindowManager) {
                    if (canDrawOverlays()) {
                        createFloatView();
                    }
                }
                break;

            default:

        }
    }

    private boolean canDrawOverlays() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        if (Settings.canDrawOverlays(this)) {
            return true;
        }
        return false;
    }

    private void requestSettingCanDrawOverlays() {

        Toast.makeText(this, "请打开显示悬浮窗开关!", Toast.LENGTH_LONG).show();
        int sdkInt = Build.VERSION.SDK_INT;
        if (sdkInt >= Build.VERSION_CODES.M) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivityForResult(intent, REQUEST_DIALOG_PERMISSION);
        } else {//4.4-6.0一下
            //无需处理了
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mFloatLayout != null) {
            //移除悬浮窗口
            mWindowManager.removeView(mFloatLayout);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_DIALOG_PERMISSION) {
            if (resultCode == RESULT_OK) {
                btnRequestOverlays.setVisibility(View.GONE);
            } else {
                Toast.makeText(this, "需要浮窗权限来显示浮窗!", Toast.LENGTH_LONG).show();
                btnRequestOverlays.setVisibility(View.VISIBLE);
            }
        }
    }
}